package com.websocket.demo.controller;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lirenchun
 */
@Component
@ServerEndpoint("/webSocket/{username}")
public class WebSocket {
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private static int onlineCount = 0;
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        this.username = username;
        this.session = session;
        addOnlineCount();
        clients.put(username, this);
        session.getUserProperties().put("username", username);
        session.getAsyncRemote().sendText("hello,你很帅--成功连上组织");
    }

    @OnClose
    public void onClose(){
        clients.remove(username);
        subOnlineCount();

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        Map<String, Object> userProperties = session.getUserProperties();
        String username = (String) userProperties.get("username");
        System.out.println("来自"+username+"的消息:" + message);
    }


    public void sendMessage(String message) throws IOException {
        session.getAsyncRemote().sendText(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }
}
